<template>
  <div class="device-card camera-device" :class="{ 'device-on': device.status === 'on' }">
    <div class="device-header">
      <div class="device-info">
        <h4>{{ device.name }}</h4>
        <div class="device-status">
          <el-tag :type="device.status === 'on' ? 'success' : 'info'" size="small">
            {{ device.status === 'on' ? '开启' : '关闭' }}
          </el-tag>
          <el-tag v-if="device.recording" type="warning" size="small">录像中</el-tag>
        </div>
      </div>
      <div class="device-actions">
        <el-button
          :type="device.status === 'on' ? 'danger' : 'success'"
          size="small"
          @click="toggleDevice"
        >
          {{ device.status === 'on' ? '关闭' : '开启' }}
        </el-button>
        <el-button type="primary" size="small" @click="showCameraControl">
          <el-icon><VideoPlay /></el-icon>
        </el-button>
      </div>
    </div>

    <!-- 摄像头控制面板 -->
    <div v-if="showControls && device.status === 'on'" class="device-controls">
      <!-- 录像控制 -->
      <div class="control-group">
        <label>录像控制</label>
        <el-button
          :type="device.recording ? 'danger' : 'success'"
          size="small"
          @click="toggleRecording"
          :loading="recording"
        >
          {{ device.recording ? '停止录像' : '开始录像' }}
        </el-button>
      </div>

      <!-- 拍照 -->
      <div class="control-group">
        <label>拍照</label>
        <el-button
          type="primary"
          size="small"
          @click="takePhoto"
          :loading="takingPhoto"
        >
          <el-icon><Camera /></el-icon>拍照
        </el-button>
      </div>

      <!-- 夜视模式 -->
      <div class="control-group">
        <label>夜视模式</label>
        <el-switch
          :model-value="device.nightVision"
          @change="updateNightVision"
        />
      </div>

      <!-- 分辨率设置 -->
      <div class="control-group">
        <label>分辨率设置</label>
        <el-select :model-value="device.resolution" @change="updateResolution">
          <el-option label="高清 1080P" value="1080p"></el-option>
          <el-option label="标清 720P" value="720p"></el-option>
          <el-option label="低清 480P" value="480p"></el-option>
        </el-select>
      </div>

      <!-- 巡航控制 -->
      <div class="control-group">
        <label>巡航模式</label>
        <el-button
          :type="device.patrolling ? 'danger' : 'primary'"
          size="small"
          @click="togglePatrol"
          :loading="patrolling"
        >
          {{ device.patrolling ? '停止巡航' : '开始巡航' }}
        </el-button>
      </div>

      <!-- 角度调节 -->
      <div class="control-group">
        <label>角度调节</label>
        <div class="angle-controls">
          <div class="angle-control">
            <label>水平角度</label>
            <el-slider
              :model-value="device.pan"
              :min="-180"
              :max="180"
              :step="5"
              @change="updateAngle"
              show-input
              :show-input-controls="false"
            />
          </div>
          <div class="angle-control">
            <label>垂直角度</label>
            <el-slider
              :model-value="device.tilt"
              :min="-90"
              :max="90"
              :step="5"
              @change="updateAngle"
              show-input
              :show-input-controls="false"
            />
          </div>
        </div>
      </div>
    </div>
    
    <div class="device-actions">
      <el-button type="danger" size="small" @click="removeDevice">
        <el-icon><Delete /></el-icon>
        删除
      </el-button>
    </div>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { VideoPlay, Camera, Delete } from '@element-plus/icons-vue'
import { useDeviceStore } from '../../store/deviceStore.js'

export default {
  name: 'CameraDevice',
  components: {
    VideoPlay,
    Camera,
    Delete
  },
  props: {
    device: {
      type: Object,
      required: true
    }
  },
  emits: ['update:device'],
  setup(props, { emit }) {
    const deviceStore = useDeviceStore()
    const showControls = ref(false)
    const recording = ref(false)
    const takingPhoto = ref(false)
    const patrolling = ref(false)

    // 初始化摄像头状态
    const initCameraStatus = async () => {
      try {
        const status = await deviceStore.getCameraStatus(props.device.id)
        if (status) {
          // 更新设备状态
          const updatedDevice = { ...props.device, ...status }
          emit('update:device', updatedDevice)
        }
      } catch (error) {
        console.warn('获取摄像头状态失败:', error.message)
      }
    }

    // 组件挂载时获取初始状态
    onMounted(() => {
      initCameraStatus()
    })

    // 切换设备开关状态
    const toggleDevice = async () => {
      try {
        await deviceStore.toggleDevice(props.device.id)
        const updatedDevice = { ...props.device }
        emit('update:device', updatedDevice)
      } catch (error) {
        ElMessage.error('设备控制失败：' + error.message)
      }
    }

    // 显示摄像头控制面板
    const showCameraControl = () => {
      showControls.value = !showControls.value
    }

    // 切换录像状态
    const toggleRecording = async () => {
      recording.value = true
      try {
        await deviceStore.controlSmartCamera(props.device.id, 'record',
          props.device.recording ? 'stop' : 'start')
        const updatedDevice = { ...props.device }
        updatedDevice.recording = !props.device.recording
        emit('update:device', updatedDevice)
      } catch (error) {
        ElMessage.error('录像控制失败：' + error.message)
      } finally {
        recording.value = false
      }
    }

    // 拍照
    const takePhoto = async () => {
      takingPhoto.value = true
      try {
        const result = await deviceStore.controlSmartCamera(props.device.id, 'snapshot')
        ElMessage.success('拍照成功')

        if (result.photoUrl) {
          console.log('照片URL:', result.photoUrl)
          // 可以在这里添加照片预览或下载逻辑
        }
      } catch (error) {
        ElMessage.error('拍照失败：' + error.message)
      } finally {
        takingPhoto.value = false
      }
    }

    // 更新夜视模式
    const updateNightVision = async (enabled) => {
      try {
        await deviceStore.controlSmartCamera(props.device.id, 'night_vision', enabled)
        const updatedDevice = { ...props.device, nightVision: enabled }
        emit('update:device', updatedDevice)
        ElMessage.success(`夜视模式已${enabled ? '开启' : '关闭'}`)
      } catch (error) {
        ElMessage.error('夜视模式更新失败：' + error.message)
      }
    }

    // 更新分辨率
    const updateResolution = async () => {
      try {
        await deviceStore.controlSmartCamera(props.device.id, 'resolution', props.device.resolution)
        const updatedDevice = { ...props.device }
        emit('update:device', updatedDevice)
      } catch (error) {
        ElMessage.error('分辨率更新失败：' + error.message)
      }
    }

    // 更新角度
    const updateAngle = async () => {
      try {
        await deviceStore.controlSmartCamera(props.device.id, 'pan', props.device.pan)
        await deviceStore.controlSmartCamera(props.device.id, 'tilt', props.device.tilt)
        const updatedDevice = { ...props.device }
        emit('update:device', updatedDevice)
      } catch (error) {
        ElMessage.error('角度调节失败：' + error.message)
      }
    }

    // 切换巡航状态
    const togglePatrol = async () => {
      patrolling.value = true
      try {
        const action = props.device.patrolling ? 'patrol_stop' : 'patrol_start'
        await deviceStore.controlSmartCamera(props.device.id, action, true)
        const updatedDevice = { ...props.device }
        updatedDevice.patrolling = !props.device.patrolling
        emit('update:device', updatedDevice)
        ElMessage.success(`巡航${props.device.patrolling ? '停止' : '开始'}成功`)
      } catch (error) {
        ElMessage.error('巡航控制失败：' + error.message)
      } finally {
        patrolling.value = false
      }
    }

    // 删除设备
    const removeDevice = () => {
      deviceStore.removeDevice(props.device.id)
    }

    return {
      showControls,
      recording,
      takingPhoto,
      patrolling,
      toggleDevice,
      showCameraControl,
      toggleRecording,
      takePhoto,
      updateNightVision,
      updateResolution,
      updateAngle,
      togglePatrol,
      removeDevice
    }
  }
}
</script>

<style scoped>
.device-card.camera-device {
  border-left: 4px solid #9c27b0;
}

.device-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 15px;
}

.device-info h4 {
  margin: 0 0 5px 0;
  color: #333;
}

.device-status {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.device-actions {
  display: flex;
  gap: 8px;
}

.device-controls {
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px solid #e0e0e0;
}

.control-group {
  margin-bottom: 15px;
}

.control-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: #333;
}

.control-group .el-switch {
  margin-top: 8px;
}

.angle-controls {
  display: flex;
  gap: 15px;
}

.angle-control {
  flex: 1;
}

.angle-control .el-slider {
  margin-top: 8px;
}

.device-card.device-on {
  background: linear-gradient(135deg, #f3e5f5 0%, #e1bee7 100%);
}

.device-card.device-off {
  background: #f8f9fa;
}

.device-actions {
  margin-top: 15px;
  text-align: right;
}
</style>
